package com.home.demo.fitler;

import com.alibaba.fastjson.JSONObject;
import com.home.demo.common.JwtUtil;
import com.home.demo.common.RedisCache;
import com.home.demo.common.ResponseCode;
import com.home.demo.entity.vo.user.UserLoginVO;
import io.jsonwebtoken.SignatureException;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Component
public class UserOperationInterceptor extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");

//        if (!request.getServletPath().equals("/user/login") && !request.getServletPath().equals("/teacher/user/save")&&!StringUtils.hasText(token)){
//            responseMap(response,"请注意,不要干违法的事情");
//            return;
//        }
        if (!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }
        String subject;
        try {
            //解析token获取id
            subject = JwtUtil.parseJWT(token).getSubject();

        } catch (SignatureException e) {
            responseMap(response,"token非法,请注意");
            return;
        }
        //查询登陆状态
        UserLoginVO loginUser = redisCache.getCacheObject(subject);
        if (Objects.isNull(loginUser)) {
            responseMap(response,"账号未登录");
            return;
        }
        filterChain.doFilter(request,response);
    }

    private void responseMap(HttpServletResponse response,String msg) throws IOException {
        Map<String, Object> map = new HashMap();
        map.put("code", ResponseCode.ERR.getCode());
        map.put("msg", msg);
        String s = JSONObject.toJSONString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(s);
        response.getWriter().close();
    }


}
